template
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="分类名称" prop="itemTypeName">
        <el-input
          v-model="queryParams.itemTypeName"
          placeholder="请输入产品物料类型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="enableFlag">
        <el-select v-model="queryParams.enableFlag" placeholder="请选择是否启用" clearable>
          <el-option
            v-for="dict in dict.type.md_measure_enableflag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="typeList"
      row-key="itemTypeId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="itemTypeName" label="分类" sortable width="180"></el-table-column>
      <el-table-column prop="orderNum" label="排序" sortable width="180"></el-table-column>
      <el-table-column prop="itemOrProduct" label="物料/产品">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.md_type_item_or_product" :value="scope.row.itemOrProduct"/>
        </template>
      </el-table-column>
      <el-table-column prop="enableFlag" label="是否启用">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.md_measure_enableflag" :value="scope.row.enableFlag"/>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['md:type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['md:type:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['md:type:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改物料产品分类对话框 -->
    <!-- 添加或修改物料产品分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <!-- 给form添加自定义类，方便统一控制样式 -->
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="custom-type-form"
      >
      <el-form-item label="产品物料类型编码" prop="itemTypeCode">
        <el-input
          v-model="form.itemTypeCode"
          placeholder="请输入产品物料类型编码"
          style="width: 320px;"
        />
      </el-form-item>
      <el-form-item label="产品物料类型名称" prop="itemTypeName">
        <el-input
          v-model="form.itemTypeName"
          placeholder="请输入产品物料类型名称"
          style="width: 320px;"
        />
      </el-form-item>
      <el-form-item label="父类型ID" prop="parentTypeId">
        <treeselect
          v-model="form.parentTypeId"
          :options="typeOptions"
          :normalizer="normalizer"
          placeholder="请选择父类型ID"
          style="width: 320px;"
        />
      </el-form-item>
      <el-form-item label="产品物料标识" prop="itemOrProduct">
        <el-select
          v-model="form.itemOrProduct"
          placeholder="请选择产品物料标识"
          style="width: 320px;"
        >
        <el-option
          v-for="dict in dict.type.md_type_item_or_product"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
        </el-select>
      </el-form-item>
      <el-form-item label="排列顺序" prop="orderNum">
        <el-input-number
          v-model="form.orderNum"
          controls-position="right"
          :min="0"
          style="width: 320px;"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="enableFlag">
        <el-select
          v-model="form.enableFlag"
          placeholder="请选择是否启用"
          style="width: 320px;"
        >
        <el-option
          v-for="dict in dict.type.md_measure_enableflag"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入内容"
          style="width: 320px; min-height: 80px;"
        />
      </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType } from "@/api/md/type"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "Type",
  dicts: ['md_type_item_or_product', 'md_measure_enableflag'],
  components: {
    Treeselect
  },
  data() {
    return {
      loading: true,
      showSearch: true,
      typeList: [],
      typeOptions: [],
      title: "",
      open: false,
      isExpandAll: true,
      refreshTable: true,
      queryParams: {
        itemTypeCode: '',
        itemTypeName: '',
        parentTypeId: '',
        ancestors: '',
        itemOrProduct: '',
        orderNum: '',
        enableFlag: ''
      },
      form: this.getDefaultForm(),
      rules: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getDefaultForm() {
      return {
        itemTypeId: null,
        itemTypeCode: '',
        itemTypeName: '',
        parentTypeId: null,
        ancestors: '',
        itemOrProduct: '',
        orderNum: 0,
        enableFlag: '',
        remark: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },
    getList() {
      this.loading = true
      listType(this.queryParams)
        .then(response => {
          this.typeList = this.handleTree(response.data, "itemTypeId", "parentTypeId")
          this.loading = false
        })
        .catch(error => {
          console.error('获取列表失败:', error)
          this.loading = false
        })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.itemTypeId,
        label: node.itemTypeName,
        children: node.children
      }
    },
    buildRootNode(data) {
      return {
        itemTypeId: 0,
        itemTypeName: '顶级节点',
        children: this.handleTree(data, "itemTypeId", "parentTypeId")
      }
    },
    getTreeselect() {
      listType()
        .then(response => {
          this.typeOptions = [this.buildRootNode(response.data)]
        })
        .catch(error => {
          console.error('获取树形结构失败:', error)
        })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = this.getDefaultForm()
      this.resetForm("form")
    },
    handleQuery() {
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      this.form.parentTypeId = row?.itemTypeId || 0
      this.open = true
      this.title = "添加物料产品分类"
    },
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      setTimeout(() => {
        this.refreshTable = true
      }, 0)
    },
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      getType(row.itemTypeId)
        .then(response => {
          this.form = response.data
          this.form.parentTypeId = row.parentTypeId
          this.open = true
          this.title = "修改物料产品分类"
        })
        .catch(error => {
          console.error('加载详情失败:', error)
        })
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return
        const apiCall = this.form.itemTypeId ? updateType : addType
        apiCall(this.form)
          .then(() => {
            this.$modal.msgSuccess(`${this.form.itemTypeId ? '修改' : '新增'}成功`)
            this.open = false
            this.getList()
          })
          .catch(error => {
            console.error('保存失败:', error)
          })
      })
    },
    handleDelete(row) {
      this.$modal.confirm(`是否确认删除物料产品分类编号为"${row.itemTypeId}"的数据项？`)
        .then(() => delType(row.itemTypeId))
        .then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        })
        .catch(() => {})
    }
  }
}
</script>
<style scoped>
.custom-type-form {
  padding: 0 20px;  /* 给表单左右加内边距，避免贴边 */
}
.custom-type-form .el-form-item {
  margin-bottom: 16px;  /* 减小表单项之间的间距，更紧凑 */
}
</style>
